<template>
  <div>
    <!--
      show-checkbox: 显示复选框
      default-expand-all: 默认展开所有子节点
      check-strictly: 父子节点不要相互关联
     -->
    <!-- node-key="id": 指定当前 tree 的数据中唯一标示属性名 -->
    <el-tree
      ref="permTree"
      show-checkbox
      default-expand-all
      check-strictly
      :data="list"
      :props="{ label: 'name' }"
      node-key="id"
    />
    <div style="margin-top: 20px; text-align: right">
      <el-button type="primary" @click="hSubmit">确定</el-button>
      <el-button @click="$emit('close')">取消</el-button>
    </div>
  </div>
</template>

<script>
import { getPermissionList } from '@/api/permissions'
import { tranListToTreeData } from '@/utils'
import { assignPerm, getRoleDetailById } from '@/api/roles'
export default {
  props: {
    roleId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      list: []
    }
  },
  created() {
    // 获取所有的权限点
    this.loadPermissions()
    // 获取当前点击的角色所拥有的所有权限
    this.loadRoleDetail()
  },
  methods: {
    async loadPermissions() {
      const res = await getPermissionList().catch((e) => e)
      if (!res.success) return
      // console.log(tranListToTreeData(res.data))
      this.list = tranListToTreeData(res.data)
    },
    async loadRoleDetail() {
      const res = await getRoleDetailById(this.roleId).catch((e) => e)
      if (!res.success) return
      // console.log(res.data.permIds)
      // 数据回填
      this.$refs.permTree.setCheckedKeys(res.data.permIds)
    },
    async hSubmit() {
      // 用户点击确定
      // 获取用户勾选的权限 id 列表
      const permIds = this.$refs.permTree.getCheckedKeys()

      // console.log(result)
      // 发请求 id: 角色 id
      const res = await assignPerm({ id: this.roleId, permIds }).catch((e) => e)

      // 提醒用户
      if (!res.success) return this.$message.error(res.message)
      this.$message.success(res.message)

      // 关闭 dialog
      this.$emit('close')
    }
  }
}
</script>
